package com.base.flowable.flowable.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SimplePropertyPreFilter;

import java.util.Arrays;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Json工具
 *
 * @author liuyazhou
 * @date 2018/07/11
 */
public class JsonUtils {
    private JsonUtils() {
    }

    /**
     * 保留某些字段
     *
     * @param target 目标对象
     * @param fields 字段
     * @return 保留字段后的对象
     */
    public static <T> T keepFields(final Object target, final Class<T> clz, final String... fields) {
        final SimplePropertyPreFilter filter = new SimplePropertyPreFilter();
        filter.getIncludes().addAll(Arrays.asList(fields));
        return done(target, clz, filter);
    }
    /**
     * 获取指定url中的某个参数
     * @param url
     * @param name
     * @return
     */
    public static String getParamByUrl(String url, String name) {
        url += "&";
        String pattern = "(\\?|&){1}#{0,1}" + name + "=[a-zA-Z0-9]*(&{1})";

        Pattern r = Pattern.compile(pattern);

        Matcher m = r.matcher(url);
        if (m.find( )) {
            return m.group(0).split("=")[1].replace("&", "");
        } else {
            return null;
        }
    }

    /**
     * 去除某些字段
     *
     * @param target 目标对象
     * @param fields 字段
     * @return 去除字段后的对象
     */
    public static <T> T deleteFields(
            final Object target, final Class<T> clz, final String... fields) {
        final SimplePropertyPreFilter filter = new SimplePropertyPreFilter();
        filter.getExcludes().addAll(Arrays.asList(fields));
        return done(target, clz, filter);
    }

    private static <T> T done(
            final Object target, final Class<T> clz, final SimplePropertyPreFilter filter) {
        final String jsonString = JSON.toJSONString(target, filter);
        return JSON.parseObject(jsonString, clz);
    }
}
